package com.systemframework.sys.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.systemframework.sys.dto.request.SysRoleRequestDTO;
import com.systemframework.sys.dto.response.SysRoleResponseDTO;
import com.systemframework.sys.entity.SysRole;
import com.systemframework.sys.entity.SysRoleMenu;
import com.systemframework.sys.mapper.SysRoleMapper;
import com.systemframework.sys.service.SysRoleMenuService;
import com.systemframework.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author summer
 * @date 2023-03-20 13:32
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper,SysRole> implements SysRoleService {

    @Override
    public Page<SysRoleResponseDTO> findLists(SysRoleRequestDTO roleRequestDTO) {
        Page<SysRole> page=new Page<>(roleRequestDTO.getPageNum(),roleRequestDTO.getPageSize());
        LambdaQueryWrapper<SysRole> sysRoleLambdaQueryWrapper = Wrappers.lambdaQuery(SysRole.class).like(StrUtil.isNotEmpty(roleRequestDTO.getName()),SysRole::getName,roleRequestDTO.getName());
        page = this.page(page, sysRoleLambdaQueryWrapper);
        return Convert.convert(new TypeReference<Page<SysRoleResponseDTO>>() {},page);
    }

    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    public void setSysRoleMenuService(SysRoleMenuService sysRoleMenuService) {
        this.sysRoleMenuService = sysRoleMenuService;
    }

    @Override
    public void saveRoleAndMenus(SysRoleRequestDTO sysRoleRequestDTO) {
        LambdaQueryWrapper<SysRoleMenu> eq = Wrappers.lambdaQuery(SysRoleMenu.class).eq(SysRoleMenu::getRoleId, sysRoleRequestDTO.getId());
        sysRoleMenuService.remove(eq);
        List<Integer> menuIds = sysRoleRequestDTO.getMenuIds();
        List<SysRoleMenu> list = ListUtil.list(true);
        menuIds.forEach(menuId->{
           list.add(new SysRoleMenu(sysRoleRequestDTO.getId(),menuId));
       });
        sysRoleMenuService.saveBatch(list);
    }
}
